package com.yin.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;

//拦截器！！
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权：首页所有人可以访问，但是功能页只有对应权限的人可以访问
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("v1")
                .antMatchers("/level2/**").hasRole("v2")
                .antMatchers("/level3/**").hasRole("v3");

        //没有权限时点击任何页面都会默跳会到登录页面,需要开启登录的页面
        http.formLogin().loginPage("/toLogin");

        //注销功能,删除cookie移除session信息，返回到首页
        http.logout().deleteCookies("remove").logoutSuccessUrl("/");

        //安全问题，防止网站因为get请求收到攻击，关闭csrf功能
        http.csrf().disable();

        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证,不同身份权限的用户获得不同的权限
    //这里会遇到密码编码的错误PasswordEncoder，在spring security5.0+中，只需要将密码加密即可
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //正常来说，这些数据应该从数据库中获取，但是重写的方法有这样的测试功能可以尝试
        auth.inMemoryAuthentication().passwordEncoder(new Pbkdf2PasswordEncoder())
                .withUser("yinkuo").password(new Pbkdf2PasswordEncoder().encode("123456")).roles("v2", "v3")
                .and()
                .withUser("root").password(new Pbkdf2PasswordEncoder().encode("111111")).roles("v1", "v2", "v3")
                .and()
                .withUser("xiaobai").password(new Pbkdf2PasswordEncoder().encode("222222")).roles("v1");
    }
}
